package com.foreverwin.jzymes.websocket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.foreverwin.jzymes.common.mapper.DashBoardAdviceMapper;
import com.foreverwin.jzymes.common.mapper.SfcBatchPassLogAdviceMapper;
import com.foreverwin.jzymes.common.service.*;
import com.foreverwin.jzymes.common.util.BOHandleUtil;
import com.foreverwin.jzymes.framework.annotation.WebSocketHandler;
import com.foreverwin.jzymes.framework.event.AppEvent;
import com.foreverwin.jzymes.framework.websocket.TextMessageWebSocketWraper;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@WebSocketHandler(channel = "Z_DB_AUTO_EQU_OEE")
public class AutoEquipOEEHandler extends TextMessageWebSocketWraper {

    @Autowired
    IActivityRuleAdviceService activityRuleAdviceService;
    @Autowired
    IItemGroupAdviceService itemGroupAdviceService;
    @Autowired
    ICustomFieldsAdviceService customFieldsAdviceService;
    @Autowired
    ICommonService commonService;
    @Autowired
    IProductionShiftService productionShiftService;
    @Autowired
    IResourceAdviceService resourceAdviceService;
    @Autowired
    DashBoardAdviceMapper dashBoardAdviceMapper;
    @Autowired
    SfcBatchPassLogAdviceMapper sfcBatchPassLogAdviceMapper;

    private Map<String,String> activityRuleMap;

    public AutoEquipOEEHandler(){
        events = new ArrayList();
        events.add( "RESOURCE_STATUS_CHANGE" );
    }

    @Override
    public void doAfterOpen(Connection connection) {
        activityRuleMap = activityRuleAdviceService.findActivityRules( getChannel() );
    }

    @Override
    public void doAfterClose() {

    }

    @Override
    public JSONObject doReceiveAndReply(String messageType, JSONObject requestParams) {
        if( "WS_INIT_DATA".equals( messageType ) ){
            buildAutoEquipOeeData();
        }
        return null;
    }

    @Override
    public void onAppEvent(AppEvent<?> appEvent) {
        String event = appEvent.getName();
        JSONObject eventData = (JSONObject) appEvent.getData();

        if( "RESOURCE_STATUS_CHANGE".equals( event ) ){
            String site = eventData.getString( "SITE" );
            String resrce = eventData.getString( "RESRCE" );
            String status = eventData.getString( "STATUS" );

            JSONObject cnc = new JSONObject();
            cnc.put( "id", resrce );
            cnc.put("status", status );
            JSONArray cncs = new JSONArray();
            cncs.add( cnc );
            JSONObject response = new JSONObject();
            response.put( "cncs", cncs );
            sendMessage( "WS_RESOURCE_STATUS", response );
        }
    }

    /**
     * 统计每班自动线cnc设备稼动率
     * 计划运行时间和实际运行时间均以分钟为单位
     *
     */
    public void buildAutoEquipOeeData(){
        String site = activityRuleMap.get( "SITE" );
        String workCenter = activityRuleMap.get( "WORK_CENTER" );

        Date now = new Date();
        int timeUnit = 60 * 1000;
        Date[] dateRange = productionShiftService.findShiftRange( site, now );
        Long planRunTime = ( dateRange[1].getTime() - dateRange[0].getTime() ) / timeUnit;

        JSONArray cncs = new JSONArray();
        JSONObject cncTotal = new JSONObject();
        cncTotal.put( "id", "cncTotal" );
        cncTotal.put( "plan", 0L );
        cncTotal.put( "product", 0L );

        List<Map<String,String>> cncList = dashBoardAdviceMapper.findCncResourceListByWorkCenter( BOHandleUtil.buildWorkCenterHandle( site, workCenter ) );
        for( Map<String,String> map : cncList ){
            String resource = map.get( "RESRCE" );
            Map<String,Object> resourceTimeSummary = dashBoardAdviceMapper.findResourceTimeSummary( site, resource, "RUN", dateRange[0], dateRange[1] );

            BigDecimal elapsedTime = BigDecimal.ZERO;
            if( resourceTimeSummary != null ){
                elapsedTime = (BigDecimal) resourceTimeSummary.get( "ELAPSED_TIME" );
            }

            JSONObject cnc = new JSONObject();
            cnc.put( "id", resource );
            cnc.put( "status", resourceAdviceService.findResourceStatus( site, resource ) );
            cnc.put( "plan", planRunTime );
            cnc.put( "product", elapsedTime );
            cnc.put( "rate", String.format( "%.2f%%", elapsedTime.divide( BigDecimal.valueOf( cnc.getLong( "plan" ) ), 4, BigDecimal.ROUND_HALF_UP ).multiply( BigDecimal.valueOf( 100 ) ) ) );
            cncs.add( cnc );

            cncTotal.put( "plan", cncTotal.getLong( "plan" ) + cnc.getLong( "plan" ) );
            cncTotal.put( "product", cncTotal.getLong( "product" ) + cnc.getLong( "product" ) );

        }

        cncTotal.put( "rate", String.format( "%.2f%%", BigDecimal.valueOf( cncTotal.getLong( "product" ) ).divide( BigDecimal.valueOf( cncTotal.getLong( "plan" ) ), 4, BigDecimal.ROUND_HALF_UP ).multiply( BigDecimal.valueOf( 100 ) ) ) );
        cncs.add( cncTotal );

        JSONObject response = new JSONObject();
        response.put( "cncs", cncs );
        sendMessage( response );
    }

}
